package com.lagou.ipersistence.scripting;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Yan Jiahong
 * Created on 2020/11/22
 */
public class LanguageDriverRegistry {
    
    private final Map<Class<? extends LanguageDriver>, LanguageDriver> LANGUAGE_DRIVER_MAP = new HashMap<>();
    
    private Class<? extends LanguageDriver> defaultDriverClass;
    
    public void register(Class<? extends LanguageDriver> clazz) {
        if (clazz == null) {
            throw new IllegalArgumentException("null不是一个合法的参数");
        }
        if (!LANGUAGE_DRIVER_MAP.containsKey(clazz)) {
            try {
                LANGUAGE_DRIVER_MAP.put(clazz, clazz.newInstance());
            } catch (Exception e) {
                throw new ScriptingException("为类" + clazz.getName() + "加载语言驱动器失败!", e);
            }
        }
    }
    
    public LanguageDriver getDriver(Class<? extends LanguageDriver> clazz) {
        return LANGUAGE_DRIVER_MAP.get(clazz);
    }
    
    public LanguageDriver getDefaultDriver() {
      return   getDriver(defaultDriverClass);
    }
    
    public void setDefaultDriverClass(Class<? extends LanguageDriver> defaultDriverClass) {
        register(defaultDriverClass);
        this.defaultDriverClass = defaultDriverClass;
    }
}
